import { useStore } from 'vuex'
import { computed } from 'vue'
// 购物车相关逻辑
export const useCommonCartEffect = (shopId) => {
    const store = useStore()
    const cartList = store.state.cartList;
    const changeCartItemInfo = (shopId, productId, item, num) => {
        store.commit('changeCartItem', { shopId, productId, item, num });
    }
    const total = computed(() => {
        const productList = cartList[shopId]?.productList;
        let count = 0;
        let sum = 0;
        let allChecked = true;
        if (productList) {
            for (let i in productList) {
                const product = productList[i];
                count += product.count;
                if (product.check) {
                    sum += (product.count * product.price);
                }
                if (product.count > 0 && !product.check) {
                    allChecked = false;
                }
            }
        }
        sum = sum.toFixed(2);
        return { count, sum, productList, allChecked };
    });

    const productList = computed(()=>{
        let productList = cartList[shopId]?.productList || {};
        const obj = {}
        for(let i in productList){
            const product = productList[i];
            if(product.count>0){
                obj[i] = product;
            }
        }
        productList = obj;
        // console.log(productList);
        return productList;
    })
    const shopName = computed(()=>{
        const shopName = cartList[shopId]?.shopName;
        return shopName;
    })

    return { changeCartItemInfo, cartList, total,productList,shopName }
}